#!/bin/bash

echo "=== protoc-gen-msg-handler Example Build Script ==="
echo "This script demonstrates how to use protoc-gen-msg-handler"
echo

# Check if protoc is available
if ! command -v protoc &> /dev/null; then
    echo "❌ Error: protoc is not installed or not in PATH"
    echo "Please install Protocol Buffers compiler (protoc) first"
    exit 1
fi

echo "✓ protoc found: $(protoc --version)"

# Check if the plugin binary exists
PLUGIN_NAME="protoc-gen-msg-handler"
if [[ "$OSTYPE" == "msys" || "$OSTYPE" == "win32" ]]; then
    PLUGIN_NAME="protoc-gen-msg-handler.exe"
fi

if [ ! -f "../$PLUGIN_NAME" ]; then
    echo "❌ Error: $PLUGIN_NAME not found in parent directory"
    echo "Please ensure the plugin binary is available"
    exit 1
fi

echo "✓ Plugin found: ../$PLUGIN_NAME"
echo

# Create output directories
echo "📁 Creating output directories..."
mkdir -p output/go output/csharp output/typescript

# Generate Go code
echo "🚀 Generating Go code..."
protoc \
    --plugin=../$PLUGIN_NAME \
    --msg-handler_out=./output/go \
    --msg-handler_opt=lang=go \
    --proto_path=. \
    proto/game.proto

if [ $? -eq 0 ]; then
    echo "✅ Go code generated successfully"
else
    echo "❌ Failed to generate Go code"
    exit 1
fi

# Generate C# code
echo "🚀 Generating C# code..."
protoc \
    --plugin=../$PLUGIN_NAME \
    --msg-handler_out=./output/csharp \
    --msg-handler_opt=lang=csharp,csharp_namespace=Example.Game \
    --proto_path=. \
    proto/game.proto

if [ $? -eq 0 ]; then
    echo "✅ C# code generated successfully"
else
    echo "❌ Failed to generate C# code"
    exit 1
fi

# Generate TypeScript code
echo "🚀 Generating TypeScript code..."
protoc \
    --plugin=../$PLUGIN_NAME \
    --msg-handler_out=./output/typescript \
    --msg-handler_opt=lang=typescript \
    --proto_path=. \
    proto/game.proto

if [ $? -eq 0 ]; then
    echo "✅ TypeScript code generated successfully"
else
    echo "❌ Failed to generate TypeScript code"
    exit 1
fi

echo
echo "🎉 All code generation completed successfully!"
echo
echo "Generated files:"
echo "📂 Go files:"
find output/go -type f -name "*.go" | sed 's/^/   /'
echo "📂 C# files:"  
find output/csharp -type f -name "*.cs" | sed 's/^/   /'
echo "📂 TypeScript files:"
find output/typescript -type f -name "*.ts" | sed 's/^/   /'
echo
echo "You can now use these generated files in your projects!"
echo "See README.md for integration examples."